package org.dpes.compare;

import java.io.File;

import org.dpes.compare.md5.MD5Gen;
import org.dpes.compare.md5.SimpleMD5GenImpl;

class MD5Comparator extends AComparator {

	private MD5Gen generator = new SimpleMD5GenImpl();

	@Override
	CmpResult compare(File left, File right) {
		MD5Process leftProcess = new MD5Process(left);
		MD5Process rightProcess = new MD5Process(right);

		leftProcess.start();
		rightProcess.start();
		
		try {
			leftProcess.join();
			rightProcess.join();
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}

		CmpResult result = new CmpResult();
		result.setType(CmpType.MD5Cmp);

		if (leftProcess.getMD5Hash().compareToIgnoreCase(
				rightProcess.getMD5Hash()) == 0)
			result.setIdentical(true);
		else
			result.setIdentical(false);
		return result;
	}

	private class MD5Process extends Thread {

		private File file;
		private String result;

		@SuppressWarnings("unused")
		private MD5Process() {/* no default constructor */
		}

		MD5Process(File file) {
			this.file = file;
		}

		@Override
		public void run() {
			result = generator.generateMD5Hash(file);
		}

		String getMD5Hash() {
			return this.result;
		}
	}
}
